<template>
  <div class="discover-container app-background">
    <!-- 顶部标题栏 -->
    <header class="chat-list-header">
      <h1>发现</h1>
      <!-- 添加搜索图标和搜索框 -->
      <div class="search-container">
        <i
          class="search-icon"
          :class="{ active: showSearchInput }"
          @click="toggleSearch"
        ></i>
        <input
          v-if="showSearchInput"
          v-model="searchQuery"
          class="search-input"
          type="text"
          placeholder="搜索智能体..."
          ref="searchInput"
          @blur="handleSearchBlur"
        />
      </div>
    </header>


      <!-- 场景标签 -->
      <div v-if="scenes.length > 0" class="scenes-container">
        <div
          v-for="scene in scenes"
          :key="scene.id || 'all'"
          :class="['scene-tag', { active: currentSceneId === scene.id }]"
          @click="switchScene(scene.id)"
        >
          {{ scene.name }}
        </div>
      </div>


    <div class="discover-content">
      <div v-if="loading" class="loading">
        <p>加载中...</p>
      </div>
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadAgents" class="retry-button">重新加载</button>
      </div>
      <div v-else class="agents-container">
        <AgentCard
          v-for="(agent, index) in filteredAgents"
          :key="index"
          :agent="agent"
          @select="onAgentSelect"
          class="agent-card-item"
        />
      </div>
    </div>

   <!-- 修改底部导航栏 -->
<footer class="chat-list-footer">
  <div class="nav-item" :class="{ active: $route.name === 'index' }" @click="navigateTo('/')">
    <i class="nav-icon home-icon"></i>
    <span>首页</span>
  </div>
  <div class="nav-item" :class="{ active: $route.name === 'home' || $route.name === 'mobiles' }" @click="navigateTo('/mobiles')">
    <i class="nav-icon message-icon"></i>
    <span>对话</span>
  </div>
  <div class="nav-item" :class="{ active: $route.name === 'discover' }" @click="navigateTo('/discover')">
    <i class="nav-icon discover-icon"></i>
    <span>发现</span>
  </div>
</footer>

    <!-- 智能体对话窗口（核心修改区域关联） -->
    <div v-if="selectedAgent" class="agent-dialog-overlay" @click="closeAgentDialog">
      <div class="agent-dialog-fullscreen" @click.stop>
        <div class="dialog-header">
          <div class="agent-header-info">
            <!-- <div class="agent-avatar-header" :style="{ backgroundColor: selectedAgent.bgColor }">
              <i class="agent-icon-header">{{ selectedAgent.icon }}</i>
            </div> -->
            <h2>{{ selectedAgent.name }}</h2>
          </div>
          <button class="close-button" @click="closeAgentDialog">×</button>
        </div>

        <div class="dialog-content">
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="message-container bot">
              <div class="agent-avatar-message" :style="{ backgroundColor: selectedAgent.bgColor }">
                <i class="agent-icon-message">{{ selectedAgent.icon }}</i>
              </div>
              <div class="message-bubble bot">
                <div class="message-content">
                  <p>欢迎使用 {{ selectedAgent.name }}！</p>
                  <p>{{ selectedAgent.description }}</p>
                </div>
                <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
              </div>
            </div>
          </div>

          <!-- 修改消息容器部分，移除用户头像显示 -->
          <div v-else class="messages-container">
            <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message-container', message.sender]"
            >
              <!-- 只显示智能体头像，移除用户头像 -->
              <div v-if="message.sender === 'bot'" class="agent-avatar-container">
                <div class="agent-avatar-message" :style="{ backgroundColor: selectedAgent.bgColor }">
                  <i class="agent-icon-message">{{ selectedAgent.icon }}</i>
                </div>
              </div>


              <div :class="['message-bubble', message.sender]">
                <!-- 显示解析后的内容，对每部分都应用renderMarkdown -->
                <div v-if="message.parsedContent" class="message-content">
                  <template v-for="(part, partIndex) in message.parsedContent" :key="partIndex">
                    <span v-if="part.type === 'text'" v-html="renderMarkdown(part.content)"></span>
                     <!-- 为可点击部分添加独立的点击事件 -->
                    <span
                      v-else-if="part.type === 'clickable'"
                      class="clickable-text"
                      @click.stop="insertPromptToInput(part.content)"
                    >
                      {{ part.content }}
                    </span>
                  </template>
                </div>
                 <!-- 实时渲染的流式内容 -->
                  <div v-else-if="message.renderedContent" class="message-content" v-html="message.renderedContent"></div>
                  <!-- 普通消息内容，支持Markdown渲染 -->
                  <div v-else class="message-content" v-html="renderMarkdown(message.content)"></div>

                  <!-- 在AI消息气泡中嵌入用户选择界面 -->
                  <div v-if="message.showUserSelect" class="embedded-user-select">
                    <div class="select-description">{{ message.userSelectDescription }}</div>
                    <div class="select-options">
                      <button
                        v-for="option in message.userSelectOptions"
                        :key="option.key"
                        @click="handleUserSelect(option.value, index)"
                        :class="['select-option-button', { 'selected': option.selected }]"
                      >
                        {{ option.value }}
                      </button>
                    </div>
                  </div>

                  <div class="message-time">{{ message.time }}</div>
                </div>
              </div>
            </div>

        </div>

        <!-- 输入区 -->
      <div class="dialog-input">
        <input
          v-model="userInput"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
          :disabled="sending"
          lang="zh-CN"
          ref="messageInput"
        />
        <button
          @click="startSpeechInput"
          class="speech-button"
          :disabled="sending || !isSpeechSupported"
          :class="{ listening: isListening }"
          type="button"
        >
          <span class="mic-icon" :class="{ listening: isListening }"></span>
        </button>
        <button @click="sendMessage" :disabled="sending">
          {{ sending ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>


  </div>
</template>


<script>
import AgentCard from '@/components/AgentCard.vue';
import { streamFetch, SseResponseEventEnum } from '@/utils/streamFetch.js';
import { getToken, getXauatLoginToken, setToken,clearToken } from '@/utils/auth.js';

// 将全局的 renderMarkdown 函数替换为以下增强版本
function renderMarkdown(text) {
  if (!text) return '';

  // 处理JSON包装的文本内容（如历史记录）
  let processedText = text;

  try {
    // 检查是否是JSON格式的文本
    if (typeof text === 'string') {
      const trimmedText = text.trim();
      // 检查是否以 [{ 开头并以 }] 结尾
      if (trimmedText.startsWith('[{') && trimmedText.endsWith('}]')) {
        let fixedJson = trimmedText;

        try {
          // 尝试直接解析JSON
          const parsed = JSON.parse(fixedJson);
          // 确保解析成功且有内容
          if (Array.isArray(parsed) && parsed.length > 0 &&
              parsed[0].hasOwnProperty('text') &&
              parsed[0].text &&
              parsed[0].text.hasOwnProperty('content')) {
            processedText = parsed[0].text.content;
          }
        } catch (parseError) {
          // 如果解析失败，尝试修复常见的JSON问题
          // 修复未正确转义的引号
          fixedJson = fixedJson.replace(/([^\\])"/g, '$1\\"');

          // 确保开头和结尾正确
          if (!fixedJson.startsWith('[{')) {
            fixedJson = '[{' + fixedJson.substring(2);
          }

          if (!fixedJson.endsWith('}]')) {
            // 查找最后一个未转义的右花括号位置
            let lastIndex = fixedJson.length - 1;
            while (lastIndex >= 0 && fixedJson[lastIndex] !== '}' && fixedJson[lastIndex] !== ']') {
              lastIndex--;
            }
            if (lastIndex >= 0) {
              fixedJson = fixedJson.substring(0, lastIndex + 1) + '}]';
            }
          }

          // 再次尝试解析
          const parsed = JSON.parse(fixedJson);
          if (Array.isArray(parsed) && parsed.length > 0 &&
              parsed[0].hasOwnProperty('text') &&
              parsed[0].text &&
              parsed[0].text.hasOwnProperty('content')) {
            processedText = parsed[0].text.content;
          }
        }
      }
    }
  } catch (e) {
    // 如果解析失败，尝试使用正则表达式提取内容
    try {
      const contentMatch = text.match(/"content":"((?:[^"\\]|\\.)*?)"/);
      if (contentMatch && contentMatch[1]) {
        // 解码转义字符
        processedText = contentMatch[1]
          .replace(/\\n/g, '\n')
          .replace(/\\t/g, '\t')
          .replace(/\\r/g, '\r')
          .replace(/\\"/g, '"')
          .replace(/\\\\/g, '\\');
      }
    } catch (fallbackError) {
      // 如果所有方法都失败，使用原始文本
      console.warn('解析JSON格式文本失败，使用原始文本:', e);
      processedText = text;
    }
  }

  // 转义HTML特殊字符
  let result = processedText
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");

  // 处理模块标题，添加加粗效果并确保换行
  result = result.replace(/【(.*?)】/g, '<strong>【$1】</strong><br>');

  // 处理LaTeX数学公式（行内公式）- 使用MathJax格式
  result = result.replace(/\$([^$]+)\$/g, '<span class="math-inline">\\( $1 \\)</span>');

  // 处理LaTeX块级公式 - 使用MathJax格式
  result = result.replace(/\$\$([\s\S]*?)\$\$/g, '<div class="math-block">\\[ $1 \\]</div>');

  // 处理水平分隔线
  result = result.replace(/(^|\n)---(?=\n|$)/g, '$1<hr>');

  // 处理引用块
  result = result.replace(/(^|\n)> \s*(.*?)(?=\n|$)/g, '$1<blockquote>$2</blockquote>');

  // 处理标题（规范化层级）
  result = result.replace(/(^|\n)######\s+(.*?)(?=\n|$)/g, '$1<h6>$2</h6>');
  result = result.replace(/(^|\n)#####\s+(.*?)(?=\n|$)/g, '$1<h5>$2</h5>');
  result = result.replace(/(^|\n)####\s+(.*?)(?=\n|$)/g, '$1<h4>$2</h4>');
  result = result.replace(/(^|\n)###\s+(.*?)(?=\n|$)/g, '$1<h3>$2</h3>');
  result = result.replace(/(^|\n)##\s+(.*?)(?=\n|$)/g, '$1<h2>$2</h2>');
  result = result.replace(/(^|\n)#\s+(.*?)(?=\n|$)/g, '$1<h1>$2</h1>');

  // 处理粗体
  result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

  // 处理斜体
  result = result.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g, '<em>$1</em>');

  // 处理行内代码
  result = result.replace(/`([^`]+?)`/g, '<code>$1</code>');

  // 处理规范化链接格式 [text](url)
  result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');

  // 处理未格式化的链接（括号格式）（https://example.com）
  result = result.replace(/（(https?:\/\/[^)]+)）/g, '<a href="$1" target="_blank" rel="noopener">下载Word文档</a>');

  // 处理纯URL链接（以http或https开头的独立链接）
  result = result.replace(/(^|\s)(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/g, '$1<a href="$2" target="_blank" rel="noopener">$2</a>');

  // 处理特殊下载链接格式
  result = result.replace(/\[单元出题：([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">单元出题：$1（下载Word文档）</a>');

  // 处理简单的文件下载链接提示
  result = result.replace(/(下载地址|下载链接)[:：]\s*(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/gi, '$1: <a href="$2" target="_blank" rel="noopener">$2</a>');

  // 特别处理"点击下载：URL"格式
  result = result.replace(/点击下载[:：]\s*(https?:\/\/[^\s<>"{}|\\^`\[\]]+)/gi, '点击下载: <a href="$1" target="_blank" rel="noopener">$1</a>');

  // 处理换行
  result = result.replace(/\n/g, '<br>');

  return result;
}

function generateSecureRandomString(length = 24) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const randomValues = new Uint32Array(length);
  window.crypto.getRandomValues(randomValues);
  let result = "";
  randomValues.forEach((value) => {
    result += chars[value % chars.length];
  });
  return result;
}

export default {
  name: 'DiscoverView',
  components: {
    AgentCard
  },


   data() {
    return {
      agents: [],
      loading: true,
      error: null,
      selectedAgent: null,
      messages: [],
      userInput: '',
      sending: false,
      sessionId: null, // 添加会话ID
      abortController: null,
      // 场景分类相关
      scenes: [], // 场景列表
      currentSceneId: null, // 当前选中的场景ID，null表示全部
      allAgents: [], // 存储所有智能体，用于筛选
      // 语音识别相关
      isSpeechSupported: false,
      isListening: false,
      speechRecognition: null,
       // 搜索相关
      showSearchInput: false,
      searchQuery: '',
      // 添加用于保存 responseChatItemId 的变量
      currentResponseChatItemId: null,
      // 添加 flowResponsesData 变量
      flowResponsesData: null,
      showUserSelect: false,
      userSelectDescription: '',
      userSelectOptions: [],
      interactiveData: null,
    };
  },
  computed: {
    // 添加计算属性来过滤智能体
    filteredAgents() {
      // 如果有搜索查询，则根据名称过滤
      if (this.searchQuery.trim()) {
        return this.agents.filter(agent =>
          agent.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      // 否则返回所有当前场景的智能体
      return this.agents;
    }
  },

async mounted() {
  // 只执行初始化逻辑，不再尝试获取token
    await this.loadAgents();
    this.checkSpeechRecognitionSupport();

    // 检查是否有通过路由传递的 appId 参数
    const appId = this.$route.query.appId;
    if (appId) {
         // 延迟执行，确保 agents 已经加载完成
      this.$nextTick(() => {
        setTimeout(() => {
          this.openAgentByAppId(appId);
        }, 100);
      });
    }
  },
      methods: {
        navigateTo(path) {
  this.$router.push(path);
},

// 新增方法：根据 appId 打开对应的智能体
    openAgentByAppId(appId) {
        // 使用 id 字段进行匹配，而不是 appId
      const agent = this.allAgents.find(a => a.id == appId);
      if (agent) {
        console.log('自动打开智能体:', agent);
        this.onAgentSelect(agent);
      } else {
        console.warn('未找到对应 appId 的智能体:', appId);
        console.log('可用的智能体列表:', this.allAgents);
      }
    },


        insertPromptToInput(content) {
        // 将单个提示词内容填入输入框
        this.userInput = content;

        // 自动聚焦到输入框
        this.$nextTick(() => {
          const input = document.querySelector('.dialog-input input');
          if (input) {
            input.focus();
          }
        });
      },

      async loadAgents() {
      this.loading = true;
      this.error = null;

       try {
    // 获取动态token
    const token = getToken();

    // 调用真实的API获取智能体列表（使用代理路径）
    const response = await fetch('/huayun-ai/client/app/center/list', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
        'Origin': 'https://owner-b.xauat.edu.cn',
        'Referer': 'https://owner-b.xauat.edu.cn/app/list/educationAdvanced'
      },
      credentials: 'include',
      body: JSON.stringify({})
    });

        const result = await response.json();
        console.log('获取智能体列表结果:', result);

        if (result.success) {
           // 提取所有场景信息
      const scenesMap = new Map();

      // 添加"全部智能体"场景
      scenesMap.set(null, '全部');

       // 遍历所有智能体，提取场景信息
      result.data.forEach(item => {
        if (item.labelList && Array.isArray(item.labelList)) {
          item.labelList.forEach(label => {
            if (label.tenantSceneId && label.tenantSceneName) {
              // 只有当场景ID不存在时才添加，避免重复
              if (!scenesMap.has(label.tenantSceneId)) {
                scenesMap.set(label.tenantSceneId, label.tenantSceneName);
              }
            }
          });
        }
      });

       // 转换为数组格式 [{id, name}, ...]
      this.scenes = Array.from(scenesMap.entries()).map(([id, name]) => ({
        id,
        name
      }));

// 映射API数据到AgentCard组件需要的格式
      this.allAgents = result.data.map(item => {
        // 获取场景ID列表
        let sceneIds = [];
        if (item.labelList && Array.isArray(item.labelList)) {
          sceneIds = item.labelList
            .filter(label => label.tenantSceneId)
            .map(label => label.tenantSceneId);
        }

        return {
          id: item.id,
          name: item.name,
          description: item.intro || '暂无描述',
          icon: this.getIconFromName(item.name),
          bgColor: this.generateColorFromId(item.id),
          appId: item.id,
          sceneIds: sceneIds // 添加场景ID列表
        };
      });

      // 默认显示所有智能体
      this.agents = [...this.allAgents];
      console.log('处理后的agents数组:', this.agents);
      console.log('场景列表:', this.scenes);
    } else {
      throw new Error(result.msg || '获取智能体失败');
    }
  } catch (err) {
    // 检查是否是认证错误
    if (err.message.includes('401') || err.message.includes('未授权') || err.message.includes('令牌已失效')) {
      console.log('Token失效，尝试重新认证');
      // 清除本地token
      clearToken();

      // 检查是否是西安建筑科技大学域名
      const domain = window.location.hostname;
      if (domain === 'aimobiles.xauat.edu.cn') {
        // 重定向到认证服务器
        const authUrl = 'https://authserver.xauat.edu.cn/authserver/oauth2.0/authorize?response_type=code&client_id=1427671951913222144&redirect_uri=https://aimobiles.xauat.edu.cn';
        window.location.href = authUrl;
        return;
      }
    }

    this.error = '加载智能体失败，请稍后重试';
    console.error('加载智能体失败:', err);
  } finally {
    this.loading = false;
  }
},

        // 根据名称生成图标
        getIconFromName(name) {
          const iconMap = {
            '校园': '🎓',
            '宿舍': '🛏️',
            '课程': '📅',
            '图书馆': '📚',
            '成绩': '📈',
            '制度': '📜',
            '出题': '✏️',
            '助手': '🤖',
            '查询': '🔍'
          };

          for (const [key, icon] of Object.entries(iconMap)) {
            if (name.includes(key)) {
              return icon;
            }
          }

          return '🤖'; // 默认图标
        },

        // 根据ID生成背景色
        generateColorFromId(id) {
          const colors = [
            '#e3f2fd', '#f3e5f5', '#e8f5e9', '#fff3e0',
            '#fce4ec', '#f1f8e9', '#e0f7fa', '#ffebee'
          ];

          // 使用ID生成稳定的颜色索引
          let hash = 0;
          for (let i = 0; i < id.length; i++) {
            hash = id.charCodeAt(i) + ((hash << 5) - hash);
          }

          return colors[Math.abs(hash) % colors.length];
        },

        // 添加 parsePromptContent 方法
    parsePromptContent(content) {
      if (!content) return [];

      const parts = [];
      const regex = /\[(.*?)\]/g;
      let lastIndex = 0;
      let match;

      while ((match = regex.exec(content)) !== null) {
        // 添加文本部分（如果有的话）
        if (match.index > lastIndex) {
          parts.push({
            type: 'text',
            content: content.substring(lastIndex, match.index)
          });
        }

        // 添加可点击部分
        parts.push({
          type: 'clickable',
          content: match[1]
        });

        lastIndex = regex.lastIndex;
      }

      // 添加最后一段文本（如果有的话）
      if (lastIndex < content.length) {
        parts.push({
          type: 'text',
          content: content.substring(lastIndex)
        });
      }

      return parts;
    },

      async onAgentSelect(agent) {
  console.log('选中的agent:', agent);

  this.selectedAgent = agent;
  this.messages = [];
  this.userInput = '';
  this.sessionId = null;
  this.flowResponsesData = null;

  const appId = agent.id;
  if (!appId) {
    console.error('无效的appId:', appId);
    const errorMessage = {
      sender: 'bot',
      content: '智能体信息不完整，无法初始化',
      time: new Date().toLocaleTimeString()
    };
    this.messages.push(errorMessage);
    return;
  }

  console.log('使用appId初始化智能体:', appId);
  // 获取动态token
  const token = getToken();

  try {
    // 获取当前智能体的场景ID（如果有多个，使用第一个）
    let sceneId = 'personage'; // 默认值
    if (agent.sceneIds && agent.sceneIds.length > 0) {
      sceneId = agent.sceneIds[0];
    }

    // 第二步：获取系统快速数据
    const fastDataResponse = await fetch('/huayun-ai/system/fast/data', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
        'Origin': 'https://owner-b.xauat.edu.cn',
        'Referer': `https://owner-b.xauat.edu.cn/home?appId=${appId}&activeRoute=%2Fapp%2Flist&sceneId=${sceneId}`,
        'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Microsoft Edge";v="140"'
      },
      credentials: 'include',
      body: JSON.stringify({})
    });

    console.log('第二步请求完成，状态:', fastDataResponse.status);

    // 第三步：初始化智能体对话
    const initResponse = await fetch('/huayun-ai/client/chat/new/init', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
        'Origin': 'https://owner-b.xauat.edu.cn',
        'Referer': `https://owner-b.xauat.edu.cn/home?appId=${appId}&activeRoute=%2Fapp%2Flist&sceneId=${sceneId}`,
        'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Microsoft Edge";v="140"'
      },
      credentials: 'include',
      body: JSON.stringify({
        tenantAppId: appId.toString(),
        chatId: ""
      })
    });

    console.log('第三步请求完成，状态:', initResponse.status);

    const initResult = await initResponse.json();
    console.log('初始化响应:', initResult);

    if (initResult.success) {
      // 保存会话ID
      this.sessionId = initResult.data?.chatId;
      console.log('设置 sessionId 为:', this.sessionId); // 添加调试日志

      // 处理 welcomeText 字段
      const welcomeText = initResult.data?.app?.chatConfig?.welcomeText || initResult.data?.welcomeText;

      if (welcomeText) {
        // 清理文本，去除可能的换行符，但保留内容
        const cleanWelcomeText = welcomeText.trim();

        // 解析内容中的方括号
        const parsedContent = this.parsePromptContent(cleanWelcomeText);

        // 只有当确实包含可点击部分时才标记为可点击
        const isClickable = parsedContent.some(part => part.type === 'clickable');

        const welcomeMessage = {
          sender: 'bot',
          content: this.renderMarkdown(cleanWelcomeText),
          time: new Date().toLocaleTimeString(),
          clickable: isClickable,
          parsedContent: parsedContent
        };
        this.messages.push(welcomeMessage);
        console.log('添加开场白(已解析):', welcomeMessage);
      } else if (initResult.data?.welcomeMsg) {
        // 兼容旧的 welcomeMsg 字段
        const cleanWelcomeMsg = initResult.data.welcomeMsg.trim();
        const parsedContent = this.parsePromptContent(cleanWelcomeMsg);

        // 只有当确实包含可点击部分时才标记为可点击
        const isClickable = parsedContent.some(part => part.type === 'clickable');

        const welcomeMessage = {
          sender: 'bot',
          content: this.renderMarkdown(cleanWelcomeMsg), // 使用 renderMarkdown 处理
          time: new Date().toLocaleTimeString(),
          clickable: isClickable, // 只有包含可点击部分时才为true
          parsedContent: parsedContent
        };
        this.messages.push(welcomeMessage);
        console.log('添加兼容开场白:', welcomeMessage);
      }

      if (initResult.data.history && Array.isArray(initResult.data.history)) {
  const historyMessages = initResult.data.history
    .reduce((acc, record) => {
      // 检查是否有 historyPreview 字段
      if (record.responseData && Array.isArray(record.responseData)) {
        // 查找包含 historyPreview 的 AI 响应数据
        const chatNodeData = record.responseData.find(item =>
          item.moduleType === 'chatNode' &&
          item.historyPreview &&
          Array.isArray(item.historyPreview)
        );

        if (chatNodeData && chatNodeData.historyPreview) {
          // 从 historyPreview 中提取 Human 和 AI 的对话
          const previewMessages = chatNodeData.historyPreview
            .filter(preview => {
              // 只提取 AI 的回复，避免重复提取用户消息
              return preview.obj === 'AI' || preview.obj === 'System';
            })
            .map(preview => ({
              sender: 'bot',
              content: this.renderMarkdown(preview.value) || '消息内容为空',
              time: new Date(preview.time || Date.now()).toLocaleTimeString()
            }));

          acc.push(...previewMessages);
          return acc; // 关键：处理完 historyPreview 后直接返回，避免重复处理
        }
      }

      // 保持原有逻辑作为备选方案
      let content = '';
      let sender = 'bot';

      // 判断消息发送者
      if (record.obj === 'Human') {
        sender = 'user';
        // 从 value 字段获取用户消息
        if (Array.isArray(record.value)) {
          content = record.value
            .filter(item => item.type === 'text' && item.text && item.text.content)
            .map(item => item.text.content)
            .join('\n');
        } else if (typeof record.value === 'string') {
          content = record.value;
        }
      } else {
        // 从 value 字段获取 AI 回复消息
        if (Array.isArray(record.value)) {
          content = record.value
            .filter(item => item.type === 'text' && item.text && item.text.content)
            .map(item => item.text.content)
            .join('\n');
        } else if (typeof record.value === 'string') {
          content = record.value;
        } else if (record.valueJson) {
          // 兼容旧的 valueJson 字段
          try {
            const valueJson = JSON.parse(record.valueJson);
            if (Array.isArray(valueJson)) {
              content = valueJson
                .filter(item => item.type === 'text' && item.text && item.text.content)
                .map(item => item.text.content)
                .join('\n');
            } else if (typeof valueJson === 'string') {
              content = valueJson;
            }
          } catch (e) {
            content = record.valueJson;
          }
        }
      }

      const message = {
        sender: sender,
        content: this.renderMarkdown(content) || '消息内容为空',
        time: new Date(record.createTime || Date.now()).toLocaleTimeString()
      };

      // 只添加非空内容的消息
      if (message.content && message.content.trim() !== '') {
        acc.push(message);
      }

      return acc;
    }, [])
    .filter((record, index, self) => {
      // 更严格的去重逻辑：通过内容、发送者和时间戳的组合来去重
      const currentIndex = self.findIndex((item) =>
        item.content === record.content &&
        item.sender === record.sender
      );
      return currentIndex === index;
    });

  // 将历史消息添加到现有消息前面
  this.messages.unshift(...historyMessages);
}
    } else {
      throw new Error(initResult.msg || '初始化智能体失败');
    }
  } catch (err) {
    console.error('初始化智能体失败:', err);
    // 添加错误提示消息
    const errorMessage = {
      sender: 'bot',
      content: '初始化智能体失败，请稍后重试',
      time: new Date().toLocaleTimeString(),
      clickable: false
    };
    this.messages.push(errorMessage);
  }
  // 在设置完消息后触发 MathJax 渲染
  this.$nextTick(() => {
    if (window.MathJax) {
      window.MathJax.typesetPromise();
    }
  });
},

// 添加Markdown渲染方法
    renderMarkdown(text) {
      return renderMarkdown(text);
    },


    // 检查浏览器是否支持语音识别
  checkSpeechRecognitionSupport() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (SpeechRecognition) {
      this.isSpeechSupported = true;
      this.speechRecognition = new SpeechRecognition();
      this.speechRecognition.continuous = false;
      this.speechRecognition.interimResults = true;
      this.speechRecognition.lang = 'zh-CN';

      // 语音识别结果事件
      this.speechRecognition.onresult = (event) => {
        let transcript = '';
        for (let i = event.resultIndex; i < event.results.length; i++) {
          transcript += event.results[i][0].transcript;
        }
        this.userInput = transcript;
      };

      // 语音识别结束事件
      this.speechRecognition.onend = () => {
        this.isListening = false;
      };

      // 语音识别错误事件
      this.speechRecognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
        this.isListening = false;
      };
    }
  },

  // 开始语音输入
  startSpeechInput() {
    if (!this.speechRecognition) return;

    if (!this.isListening) {
      this.isListening = true;
      this.userInput = ''; // 清空当前输入
      try {
        this.speechRecognition.start();
      } catch (error) {
        console.error('启动语音识别失败:', error);
        this.isListening = false;
      }
    } else {
      this.speechRecognition.stop();
    }
  },



// 修改 closeAgentDialog 方法，确保重置 sessionId
    async closeAgentDialog() {
      // 如果正在语音识别，停止它
      if (this.speechRecognition && this.isListening) {
        this.speechRecognition.stop();
        this.isListening = false;
      }

      // 如果有正在进行的发送请求，等待其完成
      if (this.sending && this.abortController) {
        try {
          // 等待当前请求完成，最多等待5秒
          await Promise.race([
            new Promise(resolve => setTimeout(resolve, 5000)), // 最多等待5秒
            new Promise(resolve => {
              const checkComplete = () => {
                if (!this.sending) {
                  resolve();
                } else {
                  setTimeout(checkComplete, 100);
                }
              };
              checkComplete();
            })
          ]);
        } catch (e) {
          console.warn('等待发送完成时出错:', e);
        }
      }

      // 关闭对话框
      this.selectedAgent = null;
      this.messages = [];
      this.userInput = '';
      this.sessionId = null; // 重置 sessionId
      this.sending = false;
      this.abortController = null;
      this.currentResponseChatItemId = null;
      this.flowResponsesData = null;
    },


/**
   * 处理用户选择
   */
  // 修改 handleUserSelect 方法
handleUserSelect(selectedValue, messageIndex) {
  console.log('用户选择:', selectedValue);

  // 更新消息中的选项状态
  if (messageIndex !== undefined && this.messages[messageIndex]) {
    const message = this.messages[messageIndex];
    if (message.userSelectOptions) {
      // 标记选中的选项
      message.userSelectOptions = message.userSelectOptions.map(option => ({
        ...option,
        selected: option.value === selectedValue
      }));
    }
  }

  // 发送用户选择作为进一步的输入 - 使用普通的sendMessage方法
  this.userInput = selectedValue;
  this.sendMessage();
},

// 修改 sendUserSelect 方法，将其改为 sendMessage 的逻辑
async sendUserSelect(selectedValue) {
  console.log('发送用户选择:', selectedValue);

  // 直接调用 sendMessage 方法处理用户选择
  this.userInput = selectedValue;
  await this.sendMessage();
},

  /**
   * 处理交互事件
   */
  // 修改 handleInteractiveEvent 方法
    handleInteractiveEvent(event) {
      console.log('处理交互事件:', event);

      // 支持多种事件结构
      let interactiveData = null;

      if (event.interactive) {
        interactiveData = event.interactive;
      } else if (event.type && event.params) {
        interactiveData = event;
      } else {
        console.warn('收到的事件格式不符合预期:', event);
        return;
      }

   // 处理 userSelect 类型的交互（对应PC端的 InputTypeEnum.select）
  if (interactiveData.type === 'userSelect' || interactiveData.type === 'select') {
    // 保存交互数据
    this.interactiveData = interactiveData;

    // 在最后一条AI消息中添加选择界面
    if (this.messages.length > 0) {
      const lastMessage = this.messages[this.messages.length - 1];
      if (lastMessage.sender === 'bot') {
        // 初始化选项，添加selected属性
        const optionsWithSelection = (interactiveData.params?.userSelectOptions || interactiveData.params?.options || [])
          .map(option => ({
            ...option,
            selected: false
          }));

        lastMessage.showUserSelect = true;
        lastMessage.userSelectDescription = interactiveData.params?.description || '';
        lastMessage.userSelectOptions = optionsWithSelection;
      }
    }
  }
  // 处理其他类型的交互事件
  else {
    console.log('未识别的交互事件类型:', interactiveData.type, interactiveData);
  }
},



/**
 * 发送消息方法 - 使用streamFetch处理流式响应
 */
/**
 * 发送消息方法 - 完全对齐PC端流程
 * 参考PC端ChatPanel的startChat方法实现
 */
// 修改 sendMessage 方法中的机器人消息占位符创建方式
async sendMessage() {
  if (!this.userInput.trim() || this.sending) return;

  // 如果还没有 sessionId，则生成一个新的
  if (!this.sessionId) {
    this.sessionId = generateSecureRandomString();
    console.log('生成新的 sessionId:', this.sessionId);
  }

  const userMessage = this.userInput;
  this.userInput = '';
  this.sending = true;

  // 生成随机ID的辅助函数
  const generateRandomId = () => {
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  };

  const dataId = generateRandomId();
  const responseChatItemId = generateRandomId();

  // 保存 responseChatItemId 供后续使用
  this.currentResponseChatItemId = responseChatItemId;

  // 添加用户消息到界面
  const userMessageObj = {
    sender: 'user',
    content: userMessage,
    time: new Date().toLocaleTimeString()
  };
  this.messages.push(userMessageObj);

  // 创建机器人消息占位符 - 显示"正在输入中..."
  let botMessage = {
    sender: 'bot',
    content: '正在输入中...',
    renderedContent: '正在输入中...',
    time: new Date().toLocaleTimeString()
  };
  this.messages.push(botMessage);
  this.$forceUpdate();

  // 存储响应数据
  let responseText = '';
  let responseData = [];
  let isNewChat = !this.chatTitle || this.chatTitle === '新对话';

  try {
    // 创建 AbortController 用于终止请求
    this.abortController = new AbortController();

    // 构建请求数据
    const requestData = {
      chatAppId: this.selectedAgent.appId,
      value: `[{"type":"text","text":{"content":"${userMessage.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"}}]`,
      content: userMessage,
      fileKeys: [],
      messages: [{
        dataId: dataId,
        role: "user",
        hideInUI: false,
        content: userMessage
      }],
      responseChatItemId: responseChatItemId,
      variables: {
        cTime: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      },
      tenantAppId: this.selectedAgent.appId,
      chatId: this.sessionId
    };

    console.log('发送消息的请求负载:', requestData);

    // 使用streamFetch处理流式响应
    const streamResult = await streamFetch({
      url: '/huayun-ai/client/chat/completions',
      data: requestData,
      onMessage: (event) => {
        if (event.event === SseResponseEventEnum.answer ||
            event.event === SseResponseEventEnum.fastAnswer) {
          if (event.text) {
            // 如果是第一个字符，清除"正在输入中..."提示
            if (responseText === '') {
              botMessage.content = '';
              botMessage.renderedContent = '';
            }

            responseText += event.text;
            botMessage.content = responseText;
            botMessage.renderedContent = this.renderMarkdown(responseText);
            this.$forceUpdate();

            this.$nextTick(() => {
              if (window.MathJax) {
                window.MathJax.typesetPromise();
              }
            });
          }
        } else if (event.event === SseResponseEventEnum.flowResponses) {
          if (Array.isArray(event.data)) {
            responseData = event.data;
            console.log('捕获到 flowResponses 数据:', responseData);
          }
        } else if (event.event === SseResponseEventEnum.interactive) {
          console.log('交互事件:', event);
          this.handleInteractiveEvent(event);
        }
      },
      abortCtrl: this.abortController
    });

    console.log('streamFetch 完成，结果:', streamResult);

    // 对话完成后的处理
    if (responseText.trim() !== '') {
      try {
        // 1. 如果是新对话，生成标题并更新聊天记录
        if (isNewChat) {
          await this.handleNewChatCompletion(userMessage, responseText);
        } else {
          // 2. 更新现有聊天记录
          await this.updateExistingChatHistory();
        }

        // 3. 更新聊天项详情（如果有responseData）
        if (responseData && responseData.length > 0) {
          await this.updateChatItemWithResponseData(responseText, responseData);
        }

      } catch (postProcessError) {
        console.error('聊天后处理失败:', postProcessError);
      }
    }

  } catch (err) {
    // 检查是否是因为用户取消请求导致的错误
    if (err.name === 'AbortError') {
      console.log('请求已被用户取消');
      return;
    }

    console.error('发送消息失败:', err);
    botMessage.content = '抱歉，回复失败，请稍后重试';
    botMessage.renderedContent = this.renderMarkdown(botMessage.content);
    this.$forceUpdate();
  } finally {
    // 确保总是重置发送状态
    this.sending = false;
    this.abortController = null;

    // 触发 MathJax 渲染
    this.$nextTick(() => {
      if (window.MathJax) {
        window.MathJax.typesetPromise();
      }
    });
  }
},

/**
 * 使用PC端的/client/chat/once接口生成聊天标题
 * @param {string} userMessage - 用户消息
 * @param {string} aiResponse - AI回复
 */
async generateChatTitleWithAPI(userMessage, aiResponse) {
  try {
    const titlePromptTemplate = `
目标：
-通过一轮对话内容生成一个简短的标题。

回答要求：
- 标题应该与对话内容一致，且与对话内容相关。
- 标题不带标点符号。
- 标题不带任何解释性前缀。
- 标题长度少于20个字。

下面是一个对话内容：

问题:'''${userMessage}'''

回答:'''${aiResponse}'''

`;

    const { responseText } = await streamFetch({
      url: '/huayun-ai/client/chat/once',
      data: {
        content: titlePromptTemplate,
        messages: [{
          role: "user",
          content: titlePromptTemplate
        }],
        variables: {
          cTime: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-')
        },
        tenantAppId: this.selectedAgent.appId,
        chatId: this.sessionId
      },
      onMessage: () => {},
      abortCtrl: new AbortController()
    });

    if (responseText && responseText.trim()) {
      this.chatTitle = responseText.trim();
      console.log('使用API生成的标题:', this.chatTitle);
    }
  } catch (error) {
    console.error('API标题生成失败:', error);
    // 使用默认标题
    this.chatTitle = '新对话';
  }
},

/**
 * 处理新对话完成后的流程（与PC端保持一致）
 * @param {string} userMessage - 用户消息
 * @param {string} responseText - AI回复内容
 */
async handleNewChatCompletion(userMessage, responseText) {
  try {
    // 1. 生成聊天标题（使用PC端的/client/chat/once接口）
    await this.generateChatTitleWithAPI(userMessage, responseText);

    // 2. 更新聊天历史记录
    await this.updateChatHistoryRecord();

  } catch (error) {
    console.error('新对话完成处理失败:', error);
    this.chatTitle = '新对话';
  }
},

/**
 * 更新现有聊天历史记录
 */
async updateExistingChatHistory() {
  try {
    await this.updateChatHistoryRecord();
  } catch (error) {
    console.error('更新现有聊天历史记录失败:', error);
  }
},

/**
 * 更新聊天历史记录（与PC端chatUpdate保持一致）
 */
async updateChatHistoryRecord() {
  try {
    const token = getToken(); // 获取动态token
    const response = await fetch('/huayun-ai/client/chat/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        chatId: this.sessionId,
        title: this.chatTitle || '新对话',
        tenantAppId: this.selectedAgent.appId
      })
    });

    const result = await response.json();
    console.log('聊天历史记录更新结果:', result);

    if (result.success) {
      console.log('聊天历史记录更新成功');
    } else {
      console.warn('聊天历史记录更新失败:', result.msg);
    }
  } catch (error) {
    console.error('聊天历史记录更新出错:', error);
  }
},

/**
 * 更新聊天项详情（包含responseData）
 * @param {string} responseText - AI回复内容
 * @param {Array} responseData - 响应数据
 */
async updateChatItemWithResponseData(responseText, responseData) {
  try {
    if (!responseText || !this.sessionId || !this.currentResponseChatItemId) {
      console.warn('缺少必要参数，跳过聊天项更新');
      return;
    }

    const token = getToken();

    const valueContent = `[{"type":"text","text":{"content":"${responseText.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"}}]`;

    const payload = {
      dataId: this.currentResponseChatItemId,
      value: valueContent,
      content: responseText,
      responseData: JSON.stringify(responseData) // 与PC端保持一致，转换为字符串
    };

    console.log('更新聊天项的payload:', payload);

    const response = await fetch('/huayun-ai/client/chat/item/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify(payload)
    });

    const result = await response.json();
    console.log('聊天项更新结果:', result);

    if (result.success) {
      console.log('聊天项更新成功');
    } else {
      console.warn('聊天项更新失败:', result.msg);
    }
  } catch (error) {
    console.error('聊天项更新出错:', error);
  }
},

/**
 * 更新聊天历史记录（与PC端保持一致）
 * @deprecated 请使用updateChatHistoryRecord方法
 */
async updateChatHistory() {
  try {
    const token = getToken(); // 获取动态token
    const response = await fetch('/huayun-ai/client/chat/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        chatId: this.sessionId,
        title: this.chatTitle || '新对话',
        tenantAppId: this.selectedAgent.appId
      })
    });

    const result = await response.json();
    console.log('聊天历史记录更新结果:', result);

    if (result.success) {
      console.log('聊天历史记录更新成功');
    } else {
      console.warn('聊天历史记录更新失败:', result.msg);
    }
  } catch (error) {
    console.error('聊天历史记录更新出错:', error);
  }
},

/**
 * 更新聊天项详情（包含flowResponses数据）
 * @param {string} aiResponseContent - AI回复内容
 * @param {Object} flowResponsesData - 流程响应数据
 */
async updateChatItemWithFlowData(aiResponseContent, flowResponsesData) {
  try {
    if (!aiResponseContent || !this.sessionId) {
      console.warn('缺少必要参数，跳过聊天项更新');
      return;
    }

    const token = getToken();

    const dataId = this.currentResponseChatItemId;
    const valueContent = `[{"type":"text","text":{"content":"${aiResponseContent.replace(/"/g, '\\"').replace(/\n/g, '\\n')}}}]`;

    const payload = {
      dataId: dataId,
      value: valueContent,
      content: valueContent
    };

    // 处理flowResponses数据 - 按照PC端格式，responseData应该是字符串
    if (flowResponsesData !== null && flowResponsesData !== undefined) {
      let responseDataToStore;
      if (Array.isArray(flowResponsesData)) {
        responseDataToStore = flowResponsesData;
      } else if (typeof flowResponsesData === 'object') {
        responseDataToStore = [flowResponsesData];
      } else {
        responseDataToStore = [];
      }
      // 将responseData转换为字符串，与PC端保持一致
      payload.responseData = JSON.stringify(responseDataToStore);
    }

    console.log('更新聊天项的payload:', payload);

    const response = await fetch('/huayun-ai/client/chat/item/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify(payload)
    });

    const result = await response.json();
    console.log('聊天项更新结果:', result);

    if (result.success) {
      console.log('聊天项更新成功');
    } else {
      console.warn('聊天项更新失败:', result.msg);
    }
  } catch (error) {
    console.error('聊天项更新出错:', error);
  }
},

/**
 * 同步聊天记录（保留原有方法以兼容性，但标记为废弃）
 * @deprecated 请使用新的分离式方法：generateChatTitleWithAPI, updateChatHistory, updateChatItemWithFlowData
 * @param {string} aiResponseContent - AI回复内容
 * @param {Object} flowResponsesData - 流程响应数据
 * @param {string} userMessage - 用户消息内容
 */
async syncChatRecords(aiResponseContent, flowResponsesData = null, userMessage = '') {
  if (!this.sessionId) {
    console.log('没有 sessionId，跳过聊天记录同步');
    return;
  }

  const token = getToken();

  try {
    console.log('开始同步聊天记录，sessionId:', this.sessionId);

    // 获取当前智能体的场景ID
    let sceneId = 'personage'; // 默认值
    if (this.selectedAgent.sceneIds && this.selectedAgent.sceneIds.length > 0) {
      sceneId = this.selectedAgent.sceneIds[0];
    }

    // 生成对话标题
    let chatTitle = '新对话';
    if (userMessage && aiResponseContent) {
      try {
        chatTitle = await this.generateChatTitle(userMessage, aiResponseContent);
        console.log('生成的对话标题:', chatTitle);
      } catch (titleError) {
        console.warn('标题生成失败，使用默认标题:', titleError);
      }
    }

    // 第三步：如果提供了AI回复内容，则调用新的 chat/item/update 接口
    // 传递flowResponsesData给syncChatItemDetails
      if (aiResponseContent) {
        await this.syncChatItemDetails(aiResponseContent, flowResponsesData);
      }

      // 第二步：调用新增的 app/form/detail 接口
      try {
        const formDetailResponse = await fetch('/huayun-ai/client/app/form/detail', {
          method: 'POST',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
            'Content-Type': 'application/json',
            'Origin': 'https://owner-b.xauat.edu.cn',
            'Referer': `https://owner-b.xauat.edu.cn/home?appId=${this.selectedAgent.appId}&activeRoute=%2Fapp%2Flist&sceneId=${sceneId}`
          },
          credentials: 'include',
          body: JSON.stringify({
            id: parseInt(this.selectedAgent.appId) // 确保id是数字类型
          })
        });

        const formDetailResult = await formDetailResponse.json();
        console.log('表单详情接口返回结果:', formDetailResult);
      } catch (formError) {
        console.warn('表单详情接口调用失败:', formError);
        // 即使这个接口失败，我们也继续执行后续操作
      }

       // 第一步：调用原有的 chat/update 接口，使用生成的标题
      const response = await fetch('/huayun-ai/client/chat/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        chatId: this.sessionId,
        title: chatTitle // 使用生成的标题
      })
    });

    const result = await response.json();
    console.log('聊天记录同步结果:', result);

    if (result.success) {
      console.log('聊天记录同步成功');

      // 等待一小段时间确保chatItem创建完成
      await new Promise(resolve => setTimeout(resolve, 500));
    } else {
      console.warn('聊天记录同步失败:', result.msg);
    }
  } catch (error) {
    console.error('聊天记录同步出错:', error);
  }
},

 //  syncChatItemDetails 方法
    // 修改 syncChatItemDetails 方法中的 responseData 处理部分

// 修改 syncChatItemDetails 方法中的 responseData 处理部分
async syncChatItemDetails(aiResponseContent, flowResponsesData = null) {
  try {
    console.log('开始同步聊天项详细内容，收到的 flowResponsesData:', flowResponsesData);

    if (!aiResponseContent || !this.sessionId) {
      console.warn('缺少必要参数，跳过聊天项同步');
      return;
    }

    const token = getToken();

    const dataId = this.currentResponseChatItemId;
    const valueContent = `[{"type":"text","text":{"content":"${aiResponseContent.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"}}]`;

    const payload = {
      dataId: dataId,
      value: valueContent,
      content: valueContent
    };

    // 正确处理捕获到的 flowResponses 数据，确保存储在 responseData 字段下
    if (flowResponsesData !== null && flowResponsesData !== undefined) {
      let responseDataToStore;

      // 如果已经是数组，直接使用
      if (Array.isArray(flowResponsesData)) {
        responseDataToStore = flowResponsesData;
      }
      // 如果是对象，需要进一步处理
      else if (typeof flowResponsesData === 'object') {
        // 如果对象中包含data数组字段，使用该数组
        if (Array.isArray(flowResponsesData.data)) {
          responseDataToStore = flowResponsesData.data;
        }
        // 如果对象本身就是流程节点数据，包装成数组
        else if (flowResponsesData.id && flowResponsesData.nodeId && flowResponsesData.moduleName) {
          responseDataToStore = [flowResponsesData];
        }
        // 其他情况直接使用对象并包装成数组
        else {
          responseDataToStore = [flowResponsesData];
        }
      }
      // 如果是字符串，尝试解析
      else if (typeof flowResponsesData === 'string') {
        try {
          const parsed = JSON.parse(flowResponsesData);
          // 如果解析后是数组，直接使用
          if (Array.isArray(parsed)) {
            responseDataToStore = parsed;
          }
          // 如果解析后是对象，包装成数组
          else {
            responseDataToStore = [parsed];
          }
        } catch (e) {
          // 如果解析失败，将原始字符串包装成数组
          responseDataToStore = [flowResponsesData];
        }
      }
      // 其他情况包装成数组
      else {
        responseDataToStore = [flowResponsesData];
      }

      // 确保最终存储的是JSON字符串格式
      payload.responseData = JSON.stringify(responseDataToStore);
      console.log('使用处理后的 flowResponsesData 作为 responseData:', payload.responseData);
    }

    console.log('准备发送的payload:', payload);

    const itemUpdateResponse = await fetch('/huayun-ai/client/chat/item/update', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify(payload)
    });

    const itemUpdateResult = await itemUpdateResponse.json();
    console.log('聊天项详细内容同步结果:', itemUpdateResult);

    if (itemUpdateResult.success) {
      console.log('聊天项详细内容同步成功');
    } else {
      console.warn('聊天项详细内容同步失败:', itemUpdateResult.msg);
    }
    return itemUpdateResult;
  } catch (error) {
    console.error('聊天项详细内容同步出错:', error);
  }
},

/**
 * 生成对话标题
 * @param {string} userMessage - 用户消息内容
 * @param {string} aiResponse - AI回复内容
 * @returns {Promise<string>} 生成的标题
 */
async generateChatTitle(userMessage, aiResponse) {
  try {
    console.log('开始生成对话标题...');

    // 构建标题生成的提示内容
    const titlePrompt = `
目标：
-通过一轮对话内容生成一个简短的标题。

回答要求：
- 标题应该与对话内容一致，且与对话内容相关。
- 标题不带标点符号。
- 标题不带任何解释性前缀。
- 标题长度少于20个字。

下面是一个对话内容：

问题:'''${userMessage}'''

回答:'''${aiResponse}'''

`;

// 获取动态token
    const token = getToken();

    // 获取当前智能体的场景ID
    let sceneId = 'personage';
    if (this.selectedAgent.sceneIds && this.selectedAgent.sceneIds.length > 0) {
      sceneId = this.selectedAgent.sceneIds[0];
    }

    // 获取当前时间
    const currentTime = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');

     // 调用标题生成接口
    const response = await fetch('/huayun-ai/client/chat/once', {
      method: 'POST',
      headers: {
        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        content: titlePrompt,
        messages: [{
          role: "user",
          content: titlePrompt
        }],
        variables: {
          cTime: currentTime
        },
        tenantAppId: this.selectedAgent.appId.toString(),
        chatId: this.sessionId,
        detail: true,
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`标题生成接口调用失败: ${response.status}`);
    }

    // 处理流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let generatedTitle = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n');

      for (const line of lines) {
        if (line.startsWith('data: ') && line !== 'data: [DONE]') {
          try {
            const data = line.substring(6);
            const parsedData = JSON.parse(data);

            // 提取AI回复内容
            if (parsedData.choices && parsedData.choices[0] && parsedData.choices[0].delta) {
              const content = parsedData.choices[0].delta.content;
              if (content !== undefined && content !== null) {
                generatedTitle += content;
              }
            }
          } catch (e) {
            console.debug('解析标题生成数据出错:', e);
          }
        }
      }
    }

    // 清理生成的标题（去除多余的空格和换行）
    generatedTitle = generatedTitle.trim();

    // 如果标题为空，使用默认标题
    if (!generatedTitle) {
      generatedTitle = '新对话';
    }

    console.log('生成的标题:', generatedTitle);
    return generatedTitle;

  } catch (error) {
    console.error('生成标题失败:', error);
    // 返回默认标题
    return '新对话';
  }
},

 // 切换场景
  switchScene(sceneId) {
    this.currentSceneId = sceneId;

    if (sceneId === null) {
      // 显示所有智能体
      this.agents = [...this.allAgents];
    } else {
      // 筛选指定场景的智能体
      this.agents = this.allAgents.filter(agent =>
        agent.sceneIds.includes(sceneId)
      );
    }
  },
//       handlePromptClick(message) {
//   // 只处理可点击的提示词，但要确保不是由子元素触发的
//   if (message.clickable && message.sender === 'bot') {
//     // 检查事件是否由可点击文本自身触发，如果是则不处理（避免重复处理）
//     if (event && event.target && event.target.classList.contains('clickable-text')) {
//       return;
//     }

//     let contentToInsert = '';

//     // 如果有解析后的内容，提取可点击部分
//     if (message.parsedContent) {
//       // 提取所有可点击部分并连接
//       const clickableParts = message.parsedContent
//         .filter(part => part.type === 'clickable')
//         .map(part => part.content);

//       contentToInsert = clickableParts.join(''); // 连接所有可点击部分
//     } else {
//       // 否则使用完整内容
//       contentToInsert = message.content;
//     }

//     // 将提示词内容填入输入框
//     this.userInput = contentToInsert;

//     // 自动聚焦到输入框
//     this.$nextTick(() => {
//       const input = document.querySelector('.dialog-input input');
//       if (input) {
//         input.focus();
//       }
//     });
//   }
// },

    // 添加搜索相关方法
    toggleSearch() {
      this.showSearchInput = !this.showSearchInput;
      if (this.showSearchInput) {
        this.$nextTick(() => {
          this.$refs.searchInput.focus();
        });
      }
    },

    handleSearchBlur() {
      // 如果搜索框为空，隐藏搜索框
      if (!this.searchQuery) {
        this.showSearchInput = false;
      }
    },



    }
    }
</script>

<style scoped>

/* 固定场景标签栏样式 */
.sticky-scenes {
  position: sticky;
  top: 56px; /* chat-list-header 的高度 */
  z-index: 100;
  background-color: white;
  padding: 8px 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #eee;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .sticky-scenes {
    top: 52px; /* 移动端标题栏可能稍矮 */
  }
}

@media (max-width: 480px) {
  .sticky-scenes {
    top: 48px;
  }
}

/* 改进Markdown内容样式 */
.message-content h1,
.message-content h2,
.message-content h3 {
  margin: 12px 0 8px 0;
  font-weight: 600;
  color: inherit;
}

.message-content h1 {
  font-size: 1.4em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 4px;
}

.message-content h2 {
  font-size: 1.3em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 3px;
}

.message-content h3 {
  font-size: 1.2em;
}

.message-content strong {
  font-weight: 600;
}

.message-content em {
  font-style: italic;
}

.message-content code {
  background-color: #e0e0e0;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.message-content blockquote {
  border-left: 3px solid #4285f4;
  padding-left: 12px;
  margin: 8px 0;
  color: #666;
  text-align: left; /* 确保引用块左对齐 */
}

.message-content hr {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 12px 0;
}

.discover-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow-x: hidden;
  box-sizing: border-box;
  max-width: 100vw;
}

.chat-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  box-sizing: border-box;
}

.chat-list-header h1 {
  font-size: 18px;
  font-weight: 400;
  color: #333;
  margin: 0;
  letter-spacing: 1px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.discover-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px 16px 16px;
  box-sizing: border-box;
  width: 100%;
}

.loading, .error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
}

.retry-button {
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.agents-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  padding: 8px 0;
  box-sizing: border-box;
  width: 100%;
}

.agent-card-item {
  width: 100%;
}

/* 统一的底部导航栏样式 */
.chat-list-footer {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 4px 0;
  border-top: 1px solid #eee;
  background-color: #fff;
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 100;
  height: 56px;
  box-sizing: border-box;
    margin: 0;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 2px 0;
  font-style: normal;
  width: 33.333%;
}

.nav-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  color: #5f6368;
  font-size: 20px;
}

.nav-item.active .nav-icon,
.nav-item.active span {
  color: #4285f4;
  font-style: normal;
  font-weight: 600;
}

.nav-item span {
  font-size: 12px;
  color: #5f6368;
  margin-top: 4px;
  font-style: normal;
  font-weight: 500;
}

/* 首页图标 - 简洁房屋线条 */
.home-icon::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-bottom: 8px solid currentColor;
  top: -4px;
}

.home-icon::after {
  content: '';
  position: absolute;
  width: 16px;
  height: 12px;
  border: 2px solid currentColor;
  top: 4px;
}

/* 对话图标 - 简洁气泡线条 */
.message-icon::before {
  content: '';
  position: absolute;
  width: 18px;
  height: 14px;
  border: 2px solid currentColor;
  border-radius: 12px 12px 12px 0;
}

.message-icon::after {
  content: '';
  position: absolute;
  width: 6px;
  height: 6px;
  border: 2px solid currentColor;
  border-top: none;
  border-left: none;
  transform: rotate(45deg);
  bottom: -2px;
  right: 2px;
}

/* 发现图标 - 简洁放大镜线条 */
.discover-icon::before {
  content: '';
  position: absolute;
  width: 12px;
  height: 12px;
  border: 2px solid currentColor;
  border-radius: 50%;
  top: 2px;
  left: 2px;
}

.discover-icon::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 2px;
  background-color: currentColor;
  transform: rotate(45deg);
  bottom: 6px;
  right: 2px;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .chat-list-footer {
    padding: 4px 0;
    height: 56px;
  }

  .nav-item span {
    font-size: 12px;
  }

  .nav-icon {
    font-size: 20px;
  }
}

.agent-dialog-overlay {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  background-image: var(--app-background-image) !important;
  background-size: cover !important;
  background-position: center !important;
  background-repeat: no-repeat !important;
  z-index: 1000 !important;
  box-sizing: border-box !important;
  opacity: 1 !important;
}

.agent-dialog-fullscreen {
  background: rgba(255, 255, 255, 0.7) !important;
  width: 90% !important;
  height: 85% !important;
  border-radius: 16px !important;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3) !important;
  display: flex !important;
  flex-direction: column !important;
  box-sizing: border-box !important;
  margin: auto !important;
  position: absolute !important;
  overflow: hidden !important;
  z-index: 1001 !important;
}

@media (max-width: 768px) {
  .agent-dialog-fullscreen {
    width: 95% !important;
    height: 90% !important;
  }
}

@media (max-width: 480px) {
  .agent-dialog-fullscreen {
    width: 100% !important;
    height: 100% !important;
    border-radius: 0 !important;
    box-shadow: none !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 1px solid transparent;
  box-sizing: border-box;
  position: relative;
}

.agent-header-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.agent-avatar-header {
  display: none;
}

.agent-icon-header {
  font-size: 18px;
  color: #fff;
  font-style: normal;
}

.dialog-header h2 {
  margin: 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 600;
  text-align: center;
}

.close-button {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  color: #999;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  position: absolute;
  right: 16px;
}

.close-button:hover {
  color: #333;
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

.welcome-message {
  display: flex;
  justify-content: flex-start;
  padding: 10px 0;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.message-container {
  display: flex;
  gap: 8px;
  max-width: 100%;
  align-items: flex-start;
}

.message-container.bot {
  align-self: flex-start;
}

.message-container.user {
  align-self: flex-end;
  justify-content: flex-end;
  width: 100%;
}

.agent-avatar-container, .user-avatar-container {
  display: flex;
  align-items: flex-start;
  flex-shrink: 0;
  margin-top: 2px;
}

.agent-avatar-message {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  font-style: normal;
}

.user-avatar-message {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  background-color: #4285f4;
  color: white;
}

.agent-icon-message, .user-icon-message {
  font-size: 16px;
  color: #fff;
  font-style: normal;
}

.message-bubble.bot {
  background-color: transparent;
  border: none;
  border-radius: 0;
  padding: 10px 14px;
  max-width: 75%;
  word-wrap: break-word;
  box-sizing: border-box;
  box-shadow: none;
  position: relative;
}

.message-bubble.bot .message-content {
  text-align: justify;
}

.message-bubble.user {
  background-color: #ffffff;
  color: #333;
  border-radius: 18px;
  border: none;
  padding: 10px 14px;
  max-width: 75%;
  word-wrap: break-word;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  width: auto;
  min-width: 60px;
}

.message-content {
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-size: 14px;
  line-height: 1.5;
  text-align: justify;
}

.message-content p {
  margin: 0 0 6px 0;
  text-align: justify;
}

.message-content p:last-child {
  margin-bottom: 0;
}

.message-time {
  display: none;
}

.message-bubble.user .message-time {
  display: none;
}

.dialog-input {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid #eee;
  box-sizing: border-box;
  width: 100%;
  position: relative;
  z-index: 10;
}

.dialog-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
}

.dialog-input input:focus {
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}

.dialog-input button {
  padding: 8px 12px;
  border: none;
  border-radius: 8px;
  background: #4285f4;
  color: white;
  cursor: pointer;
  font-size: 14px;
}

.dialog-input button:hover:not(:disabled) {
  background-color: #3367d6;
}

.dialog-input button:disabled {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}

.clickable-text {
  color: #4285f4;
  cursor: pointer;
  text-decoration: underline;
  font-weight: 500;
}

.clickable-text:hover {
  color: #3367d6;
}

.message-bubble.user .clickable-text {
  color: #bbdefb;
  text-decoration: underline;
}

.message-bubble.user .clickable-text:hover {
  color: #90caf9;
}

@media (max-width: 768px) {
  .message-bubble.bot,
  .message-bubble.user {
    max-width: 85%;
  }

  .dialog-header h2 {
    font-size: 15px;
  }

  .message-content {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .message-bubble.bot,
  .message-bubble.user {
    max-width: 90%;
    padding: 9px 12px;
  }

  .dialog-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    box-sizing: border-box;
  }

  .agent-avatar-message, .user-avatar-message {
    width: 28px;
    height: 28px;
  }

  .dialog-input {
    padding: 10px 12px;
  }

  .dialog-input input {
    padding: 9px 12px;
    font-size: 13px;
  }

  .dialog-input button {
    padding: 9px 16px;
    font-size: 13px;
  }

  .math-inline {
    font-family: 'Times New Roman', serif;
    font-style: italic;
    background-color: #f8f9fa;
    padding: 2px 4px;
    border-radius: 3px;
    display: inline-block;
  }

  .math-block {
    font-family: 'Times New Roman', serif;
    font-style: italic;
    text-align: center;
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 5px;
    margin: 10px 0;
    overflow-x: auto;
  }

  .mjx-chtml {
    outline: 0;
  }

  .MathJax_CHTML {
    font-size: 100%;
  }

  .message-content h1,
  .message-content h2,
  .message-content h3 {
    margin: 12px 0 8px 0;
    font-weight: 600;
    color: inherit;
  }

  .message-content h1 {
    font-size: 1.4em;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 4px;
  }

  .message-content h2 {
    font-size: 1.3em;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 3px;
  }

  .message-content h3 {
    font-size: 1.2em;
  }

  .message-content strong {
    font-weight: 600;
  }

  .message-content em {
    font-style: italic;
  }

  .message-content code {
    background-color: #e0e0e0;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
  }

  .message-content blockquote {
    border-left: 3px solid #4285f4;
    padding-left: 12px;
    margin: 8px 0;
    color: #666;
    text-align: left;
  }

  .message-content hr {
    border: none;
    border-top: 1px solid #e0e0e0;
    margin: 12px 0;
  }

  .scenes-container {
  position: sticky;
  top: 56px; /* chat-list-header 的高度 */
  z-index: 100;
  /* background-color: white; */
  padding: 8px 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #eee;
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  scroll-behavior: smooth;
  overscroll-behavior-x: contain;
  box-sizing: border-box;
}

  .scenes-container::-webkit-scrollbar {
    display: none;
  }

  /* 移动端适配 */
@media (max-width: 768px) {
  .scenes-container {
    top: 52px; /* 移动端标题栏可能稍矮 */
  }
}

@media (max-width: 480px) {
  .scenes-container {
    top: 48px;
  }
}

  .scene-tag {
    padding: 6px 12px;
    background-color: transparent;
    border: none;
    border-radius: 0;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
    flex-shrink: 0;
    position: relative;
  }

  .scene-tag:hover {
    color: #333;
  }

  .scene-tag.active {
    background-color: transparent;
    color: #4285f4;
    border: none;
  }

  .scene-tag.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    height: 2px;
    background-color: #4285f4;
    border-radius: 1px;
  }

  .speech-button {
    background-color: transparent !important;
    border: none;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s ease;
    padding: 0;
    position: relative;
    border-radius: 50%;
    outline: none;
  }

  .speech-button:hover:not(:disabled) {
    background-color: #f5f5f5 !important;
  }

  .speech-button:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }

  .speech-button.listening {
    background-color: #e3f2fd !important;
  }

  .mic-icon {
    position: relative;
    width: 16px;
    height: 16px;
    border: 2px solid #5f6368;
    border-radius: 8px 8px 2px 2px;
    transition: all 0.2s ease;
  }

  .mic-icon:before {
    content: '';
    position: absolute;
    top: -6px;
    left: 50%;
    transform: translateX(-50%);
    width: 8px;
    height: 8px;
    border: 2px solid #5f6368;
    border-radius: 50%;
    background-color: white;
  }

  .mic-icon:after {
    content: '';
    position: absolute;
    bottom: -10px;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 10px;
    background-color: #5f6368;
  }

  .speech-button:hover:not(:disabled) .mic-icon,
  .speech-button:hover:not(:disabled) .mic-icon:before,
  .speech-button:hover:not(:disabled) .mic-icon:after {
    border-color: #4285f4;
    background-color: white;
    color: #4285f4;
  }

  .speech-button.listening .mic-icon,
  .speech-button.listening .mic-icon:before,
  .speech-button.listening .mic-icon:after {
    border-color: #4285f4;
    background-color: white;
    color: #4285f4;
    animation: pulse 1.5s infinite;
  }

  @keyframes pulse {
    0% {
      opacity: 1;
    }
    50% {
      opacity: 0.6;
    }
    100% {
      opacity: 1;
    }
  }

  .speech-button {
    width: 36px;
    height: 36px;
  }

  .mic-icon {
    width: 14px;
    height: 14px;
  }

  .mic-icon:before {
    width: 7px;
    height: 7px;
    top: -5px;
  }

  .mic-icon:after {
    height: 8px;
    bottom: -8px;
  }

  .search-container {
    position: relative;
    display: flex;
    align-items: center;
  }

  .search-icon {
    width: 24px;
    height: 24px;
    cursor: pointer;
    position: relative;
  }

  .search-icon::before {
    content: '';
    position: absolute;
    width: 12px;
    height: 12px;
    border: 2px solid currentColor;
    border-radius: 50%;
    top: 2px;
    left: 2px;
  }

  .search-icon::after {
    content: '';
    position: absolute;
    width: 8px;
    height: 2px;
    background-color: currentColor;
    transform: rotate(45deg);
    bottom: 6px;
    right: 2px;
  }

  .search-icon.active::before,
  .search-icon.active::after {
    display: none;
  }

  .search-input {
    padding: 6px 10px;
    border: 1px solid #ddd;
    border-radius: 16px;
    font-size: 14px;
    outline: none;
    transition: all 0.3s;
    width: 160px;
  }

  .search-input:focus {
    border-color: #4285f4;
    box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
  }

  .chat-list-header {
    padding: 12px;
  }

  .search-input {
    width: 120px;
    font-size: 13px;
    padding: 5px 8px;
  }

  .user-select-container {
    background-color: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 18px;
    border-top-left-radius: 4px;
    padding: 16px;
    margin: 10px 0;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  }

  .select-description {
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .select-options {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .select-option-button {
    padding: 10px 16px;
    background-color: #f1f3f4;
    color: #333;
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    cursor: pointer;
    font-size: 14px;
    text-align: left;
    transition: all 0.2s ease;
  }

  .select-option-button:hover {
    background-color: #e8eaed;
    border-color: #dadce0;
  }

  .embedded-user-select {
    background-color: #f8f9fa;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    padding: 12px;
    margin-top: 10px;
  }

  .embedded-user-select .select-description {
    font-size: 13px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .embedded-user-select .select-options {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .embedded-user-select .select-option-button {
    padding: 8px 12px;
    background-color: #ffffff;
    color: #333;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    cursor: pointer;
    font-size: 13px;
    text-align: left;
    transition: all 0.2s ease;
  }

  .embedded-user-select .select-option-button:hover {
    background-color: #f5f5f5;
    border-color: #bdbdbd;
  }

  .embedded-user-select .select-option-button.selected {
    background-color: #e3f2fd;
    border-color: #bbdefb;
    font-weight: 500;
  }
}
</style>
